import asyncio
import hashlib

import requests
import os
import time
import random
import sys
import json
import requests
from datetime import datetime
from PIL import Image 
BASH_DIR = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
sys.path.append(BASH_DIR)

img_id_list = []

def sha256_all_text(all_text):
    """
    sha256加密alltext
    """
    sha = hashlib.sha256()
    sha.update(all_text.encode())
    return sha.hexdigest()


# 上传
def upload_image(file_path, source_url):
    # try:
    # url = 'https://oss.jianshequan.com/api/add'
    url = 'https://oss.jianshequan.com/api/add/images'
    headers = {
        'Authorization': 'Bearer kasjdflqjkeofawejifjfglewjemrgopwekrgopwerjkgopqwerjksgogkp',
        # 'Content-Type' : 'multipart/form-data'
        # 'Authorization': 'Bearer kasjdflqjkeofawejifjfglewjemrgopwekrgopwerjkgopqwerjksgogkp'
    }
    # file = {'img_file': open(file_path, 'rb').read()}

    file = open(file_path, 'rb').read()
    # 保存完截图之后 生成一个image_id保存在数据库中
    import io
    img = Image.open(file_path, mode='r')
    imgByteArr = io.BytesIO()
    img.save(imgByteArr, format='PNG')
    imgByteArr = imgByteArr.getvalue()
    image_id = hashlib.sha256(imgByteArr).hexdigest()
    #
    print('图片ID是')
    print(image_id)
    # TODO 判断是否重复
    image_status = False
    len_id_list = len(img_id_list)
    if len_id_list >= 10:
        img_id_list.pop(0)  # 左侧出一个
        img_id_list.append(image_id)  # 右侧进一个
    else:
        img_id_list.append(image_id)  # 直接进
    if len_id_list >= 3:
        img_id_list_set = set(img_id_list)
        if len(img_id_list_set) != len_id_list:
            for id_set in img_id_list_set:
                id_count = img_id_list.count(id_set)
                if id_count >= 3:
                    image_status = True
    form_data = {
        'file_stream':file,
    }
    form_data1 = {'source_url' : source_url}

    res = requests.post(url=url, headers=headers, files=form_data, data=form_data1, verify=False)
    print('请求结果是')
    print(res.json())
    if res.status_code == 200:
    # if res.status_code == 300:
        if res.json()['code'] == 20000:
            path = res.json()['data']['file_path']
            return path, image_status
        else:
            raise Exception('图片上传异常')
    else:
        # pass
        raise Exception('图片上传异常')
# upload_image (r'E:\caijiqi_paoshuju\test.png', 'https://zjcs.cqggzy.com/cq-zjcs-pub/bidResultNotice/view/5001137500896812304180767')
def see_pic(file_path):
    url = f'https://oss.jianshequan.com/api/get'
    headers = {
        'Authorization': 'Bearer kasjdflqjkeofawejifjfglewjemrgopwekrgopwerjkgopqwerjksgogkp'
    }
    datas = {'img_path': file_path}
    res = requests.post(url=url, headers=headers, data=datas)
    if res.status_code == 200:
        if res.json()['code'] == 20000:
            print('存在:', res.json())
        else:
            raise Exception('状态码异常')
    else:
        raise Exception('状态码异常')

# 删除
def del_pic(file_path):
    url = f'https://oss.jianshequan.com/api/del'
    headers = {
        'Authorization': 'Bearer kasjdflqjkeofawejifjfglewjemrgopwekrgopwerjkgopqwerjksgogkp'
    }
    datas = {'img_path': file_path}
    res = requests.post(url=url, headers=headers, data=datas)
    print('图片删除失败')
    print(res.json())
    if res.status_code == 200:
        if res.json()['code'] == 20000:
            print('图片删除成功')
        else:
            raise Exception('图片删除失败 err info: %s' % res.text())
    else:
        raise Exception('图片删除失败 err info: %s' % res.text())

# 压缩图片
def small_pic(png_path, save_path):
    if not os.path.exists(png_path):
        raise Exception('%s:截图不存在' % png_path)
    img_size = os.stat(png_path).st_size / 1024
    im = Image.open(png_path)
    w, h = im.size
    # print(w, h)
    if 1024 < int(img_size) < 2048:
        newimg = im.resize((int(w * 0.7), int(h * 0.7)), Image.ANTIALIAS)
    elif 3096 > int(img_size) > 2048:
        newimg = im.resize((int(w * 0.8), int(h * 0.8)), Image.ANTIALIAS)
    elif int(img_size) > 3096:
        newimg = im.resize((int(w * 0.6), int(h * 0.6)), Image.ANTIALIAS)
    else:
        newimg = im.resize((int(w), int(h)), Image.ANTIALIAS)
    newimg.save(save_path)

async def _send_selenium(url, method, details_xpath, save_path,send_request_selenium):
    # send_request_selenium = ChromeHeadlessDownloader(max_=3)
    try:
        return await send_request_selenium.fetch(url, method, details_xpath, save_path, )
    except:
        pass


# 截图获取网页源码
def get_image1(url, save_path, text_xpath,send_request_selenium):
    a = 0
    while True:
        html = asyncio.run(_send_selenium(url, 'get', text_xpath, save_path, send_request_selenium))
        print("%s:::url: %s 截图完成并获取数据" % (datetime.now(), url))
        return html
        # try:
        #     pass
        # except Exception as err:
        #     a += 1
        #     if a >= 5:
        #         raise Exception('多次请求截图数据错误')
        #     time.sleep(5)

# 图片使用
def pic_use(url, save_path, item, small_path, red=0, Authorization='Bearer kasjdflqjkeofawejifjfglewjemrgopwekrgopwerjkgopqwerjksgogkp'):
    html = get_image1(url=url, save_path=save_path)
    if not html:
        raise Exception('截图异常')
    small_pic(png_path=save_path, save_path=small_path)

    path = upload_image(file_path=small_path, Authorization=Authorization)
    item['path'] = path
    if red == 0:
        del_pic(file_path=path)
    return html


def get_host_ip(time_l=1):
    """获取本机外网IP"""
    try:
        url_list = ['http://ifconfig.me/ip', 'http://jsonip.com']
        url_index = random.randint(0, 1)
        url = url_list[url_index]
        res = requests.get(url, timeout=5)
        info_str = res.content.decode(encoding='utf-8')
        if url_index == 0:
            ip = info_str.strip()
        else:
            info_dict = json.loads(info_str)
            ip = info_dict['ip']
        return ip
    except Exception as err:
        if time_l <= 10:
            time_l += 1
            return get_host_ip(time_l)
        else:
            return '0.0.0.0'

def path_file(name, picname):
    path = BASE_DIR + f'/pic/{name}_pic/pic_big'
    if not os.path.exists(path):
        os.makedirs(path)
    path1 = BASE_DIR + f'/pic/{name}_pic/pic_small'
    if not os.path.exists(path1):
        os.makedirs(path1)
    return path + f'/{picname}.png', path1 + f'/{picname}.png'

def isChinese(word):
    for ch in word.replace('-', ''):
        if '\u4e00' <= ch <= '\u9fff':
            pass
        else:
            return False
    return True
